package com.example.childpositionapp.network;

import android.annotation.SuppressLint;
import android.os.Handler;
import android.util.Log;

import androidx.annotation.Nullable;

import com.example.childpositionapp.liveData.MyLiveData;

import java.io.IOException;
import java.net.UnknownHostException;
import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.WebSocket;
import okhttp3.WebSocketListener;
import okio.ByteString;

public class InitSocketThread extends Thread {
    BackService service;
    Handler serviceHandler;
    public static boolean threadEnd = true;

    public InitSocketThread() {
    }

    public InitSocketThread(BackService service, Handler handler) {
        this.service = service;
        this.serviceHandler = handler;
    }

    @Override
    public void run() {
        super.run();
        try {
            initSocket();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 心跳检测时间
     */
    private static final long HEART_BEAT_RATE = 15 * 1000;//每隔15秒进行一次对长连接的心跳检测
    private static String WEBSOCKET_HOST_AND_PORT = "ws://175.178.213.138:8081/cjntsb/dispose";//可替换为自己的主机名和端口号
    public static WebSocket mWebSocket;

    // 初始化socket
    @SuppressLint("LongLogTag")
    public void initSocket() throws UnknownHostException, IOException {
//        MsgSend msgSend=new MsgSend(1,"开门，我是爹地");
        Log.d("INITSOCKET", "initsocket in");
        OkHttpClient client = new OkHttpClient.Builder().readTimeout(5000, TimeUnit.MILLISECONDS).connectTimeout(6000, TimeUnit.MINUTES).build();
        Request request = new Request.Builder()
                .url(WEBSOCKET_HOST_AND_PORT).build();
        Log.d("INITSOCKET", request.url().uri().toString());
        mWebSocket = client.newWebSocket(request, new WebSocketListener() {
            @Override
            public void onOpen(WebSocket webSocket, Response response) {//开启长连接成功的回调
                super.onOpen(webSocket, response);
                Log.d("INITSOCKET", "initsocket onOpen");
                mWebSocket = webSocket;
//                mWebSocket.send(gson.toJson(msgSend));  //向服务器发送id
            }

            @Override
            public void onMessage(WebSocket webSocket, String text) {//接收消息的回调
                super.onMessage(webSocket, text);
                Log.d("INITSOCKET", text);  //输入消息
                MyLiveData.getMessageData().postValue(text);
            }

            @Override
            public void onMessage(WebSocket webSocket, ByteString bytes) {
                super.onMessage(webSocket, bytes);
            }

            @Override
            public void onClosing(WebSocket webSocket, int code, String reason) {
                super.onClosing(webSocket, code, reason);
            }

            @Override
            public void onClosed(WebSocket webSocket, int code, String reason) {
                Log.d("INITSOCKET", "initsocket onClosed");
                super.onClosed(webSocket, code, reason);
            }

            @Override
            public void onFailure(WebSocket webSocket, Throwable t, @Nullable Response response) {//长连接连接失败的回调
                mWebSocket = webSocket;
                Log.d("INITSOCKET", "initsocket onFailure");
                super.onFailure(webSocket, t, response);
                t.printStackTrace();
            }
        });
        mHandler.postDelayed(heartBeatRunnable, HEART_BEAT_RATE);//开启心跳检测
    }


    private static long sendTime = 0L;
    // 发送心跳包
    private static Handler mHandler = new Handler();
    private static Runnable heartBeatRunnable = new Runnable() {
        @SuppressLint("LongLogTag")
        @Override
        public void run() {
            if (System.currentTimeMillis() - sendTime >= HEART_BEAT_RATE) {
                if (mWebSocket == null) {
                    mHandler.postDelayed(this, HEART_BEAT_RATE);//每隔一定的时间，对长连接进行一次心跳检测
                    return;
                }
//                String ping = new Gson().toJson(new MsgSend("ping",2));
                String ping = "ping";
                boolean isSuccess = mWebSocket.send(ping);//发送一个空消息给服务器，通过发送消息的成功失败来判断长连接的连接状态
                if (!isSuccess && threadEnd) {//长连接已断开
                    mHandler.removeCallbacks(heartBeatRunnable);
                    mWebSocket.cancel();//取消掉以前的长连接
                    new InitSocketThread().start();//创建一个新的连接
                } else {//长连接处于连接状态

                }
                sendTime = System.currentTimeMillis();
            }
            if (threadEnd) {
                mHandler.postDelayed(this, HEART_BEAT_RATE);//每隔一定的时间，对长连接进行一次心跳检测
            }
        }
    };


}

